package org.example.service;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.BooleanUtil;
import org.example.model.config.ExportConfig;
import org.example.model.entity.ColumnInfo;
import org.example.model.entity.TableInfo;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.io.*;
import java.util.Map;
import java.util.stream.Collectors;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.example.service.dataobject.ProjectDataObject;

/**
 * @author wuyong
 * @date 2025/6/13
 */
public class ExportService {
    public void exportTableInfo(ProjectDataObject projectDataObject, ExportConfig config) {
        List<TableInfo> tableInfos = projectDataObject.getTableInfos();
        if (tableInfos == null || tableInfos.isEmpty()) return;
        try {
            // 1. 配置FreeMarker
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
            cfg.setClassForTemplateLoading(this.getClass(), "/templates"); // 假设模板在resources/templates下
            cfg.setDefaultEncoding("UTF-8");

            // 2. 加载模板"table_info.md.ftl"
            Template template = cfg.getTemplate(config.getTemplateName());

            // 3. 构造数据
            Map<String, Object> data = new HashMap<>();
            data.put("tableInfos", tableInfos);
            data.put("columnRelations", projectDataObject.getColumnRelations());
            String outputFile = StrFormatter.format("output/{}.md", config.getFileName());
            File outputDir=  new File("output");
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }

            try(FileWriter writer = new FileWriter(outputFile, StandardCharsets.UTF_8)){
                template.process(data, writer);
            }
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
    private void processData(ProjectDataObject projectDataObject, ExportConfig config){
        if(config.isColumnHide()){
            projectDataObject.getTableInfos().forEach(tableInfo -> {
               List<ColumnInfo> columnInfos = tableInfo.getColumnInfos().stream()
                       .filter(c-> BooleanUtil.isTrue(c.getIsDisplay())).collect(Collectors.toList());
               tableInfo.setColumnInfos(columnInfos);
            });
            projectDataObject.setColumnRelations(projectDataObject.getColumnRelations().stream()
                    .filter(c-> projectDataObject.containRelation(c)).collect(Collectors.toList()));
        }

    }
}
